<template>
  <div>
    <div class="list">
      <el-card class="box-card1">
        <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
          <el-form-item label="合同名称">
            <el-input v-model="formInline.insuranceName"></el-input>
          </el-form-item>
          <el-form-item label="合同编号">
            <el-input v-model="formInline.insuranceNo"></el-input>
          </el-form-item>
          <el-form-item label="维保单位">
            <el-input v-model="formInline.maintOrgName"></el-input>
          </el-form-item>
          <el-form-item label="使用单位">
            <el-input v-model="formInline.useOrgName"></el-input>
          </el-form-item>
          <el-form-item label="保险公司">
            <el-input v-model="formInline.insuranceOrgName"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="gettableData" size="small">查询</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card class="box-card" style="margin-top:15px">
        <div style="text-align:right;">
          <el-button size="mini" type="primary" @click="addContract">添加合同</el-button>
        </div>
        <el-table :data="tableData" style="width: 100%" :header-cell-style="{
      fontWeight:800}">
          <el-table-column label="合同名称">
            <template slot-scope="scope">
              <el-button type='text' @click="showTemplateInfo(scope.row)" style="color:#0090EC;cursor: pointer;">
                {{scope.row.insuranceName}}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column prop="insuranceNo" label="合同编号">
          </el-table-column>
          <el-table-column label="合同文件">
            <template slot-scope="scope">
              <el-button type='text' @click="download(scope.row.url)" style="color:#0090EC;cursor: pointer;">
                {{scope.row.fileName}}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column prop="insuranceStarttime" label="合同开始时间">
          </el-table-column>
          <el-table-column prop="insuranceEndtime" label="合同结束时间">
          </el-table-column>
          <el-table-column prop="insuranceOrgName" label="保险公司">
          </el-table-column>
          <el-table-column prop="useOrgName" label="使用单位名称">
          </el-table-column>
          <el-table-column prop="maintOrgName" label="维保单位名称">
          </el-table-column>
          <el-table-column prop="insuranceAmount" label="保险金额">
          </el-table-column>
          <el-table-column label="操作" width="160">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="editHt(scope.row)">编辑</el-button>
              <el-button type="danger" size="mini" @click="deleteHt(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="pagination.pageNum"
          :page-size="pagination.pageSize" :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.pageTotal">
        </el-pagination>
      </el-card>
    </div>
    <el-dialog title="保险合同设备" :visible.sync="dialogVisible" :before-close="handleClose1" class="dialog4">
      <el-form :model="form" :inline="true" style="float:right">
        <el-form-item>
          <el-button type="warning" @click="getAddhtx" size="small">设备添加</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="temData" style="width: 100%" :header-cell-style="{
      fontWeight:800}">
        <el-table-column prop="eleCode" label="电梯注册代码" width="180">
        </el-table-column>
        <el-table-column prop="eleUseCommunity" label="设备地址">
        </el-table-column>
        <el-table-column prop="useOrgName" label="使用单位名称">
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template slot-scope="scope">
            <span>
              <!-- <el-button type="primary" size="mini" @click="editHtx(scope.row)" :disabled="scope.row.isSystem=='1'">编辑</el-button> -->
              <el-button type="danger" size="mini" @click="deleteHtx(scope.row.id)" :disabled="scope.row.isSystem=='1'">删除</el-button>
            </span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange1" @current-change="handleCurrentChange1" :current-page.sync="pagination1.pageNum"
        :page-size="pagination1.pageSize" :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" :total="pagination1.pageTotal"
        align='right'>
      </el-pagination>
      <el-dialog width="60%" :title="'设备'+title" :visible.sync="innerVisible" append-to-body :before-close="handleClose2">
        <el-form :inline="true" :model="temitemform" class="demo-form-inline" size="small">
          <el-form-item label="使用单位名称">
            <el-input v-model="temitemform.useOrgName"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="geteleList" size="small">查询</el-button>
          </el-form-item>
        </el-form>
        <el-table :data="eletableData" style="width: 100%" :header-cell-style="{
      fontWeight:800}" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" :selectable="selectable">
          </el-table-column>
          <el-table-column prop="eleCode" label="设备代码" width="180">
          </el-table-column>
          <el-table-column prop="useOrgName" label="使用单位名称">
          </el-table-column>
          <el-table-column prop="eleUseCommunity" label="设备地址">
          </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange2" @current-change="handleCurrentChange2" :current-page.sync="pagination2.pageNum"
          :page-size="pagination2.pageSize" :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" :total="pagination2.pageTotal"
          style="float:right">
        </el-pagination>

        <div slot="footer" class="dialog-footer">
          <el-button @click="handleClose2">取 消</el-button>
          <el-button type="primary" @click="addItemTrue" v-if="title == '添加'">确 定</el-button>
          <!-- <el-button type="primary" @click="editItemTrue" v-if="title == '编辑'">确 定</el-button> -->
        </div>
      </el-dialog>
    </el-dialog>
    <el-dialog :title="'保险合同'+title" :visible.sync="htdialog" :before-close="handleClose" class="addform">
      <el-form :model="htform" :inline="true" :rules="rules" ref="htform">
        <el-form-item label="合同名称" label-width="100px" prop="insuranceName">
          <el-input v-model="htform.insuranceName" autocomplete="off" size='small'></el-input>
        </el-form-item>
        <el-form-item label="合同编号" label-width="100px" prop="insuranceNo">
          <el-input v-model="htform.insuranceNo" autocomplete="off" size='small'></el-input>
        </el-form-item>
        <el-form-item label="合同开始时间" label-width="100px" prop="insuranceStarttime">
          <el-date-picker v-model="htform.insuranceStarttime" type="date" placeholder="选择日期" size='small' value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="合同结束时间" label-width="100px" prop="insuranceEndtime">
          <el-date-picker v-model="htform.insuranceEndtime" type="date" placeholder="选择日期" size='small' value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="使用单位" label-width="100px" prop="useOrgId">
          <el-select v-model="htform.useOrgId" placeholder="请选择" size='small' clearable>
            <el-option v-for="item in options" :key="item.useOrgId" :label="item.orgName" :value="item.useOrgId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="保险公司" label-width="100px" prop="insuranceId">
          <el-select v-model="htform.insuranceId" placeholder="请选择" size='small' clearable>
            <el-option v-for="item in insuranceArr" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="保险金额" label-width="100px" prop="insuranceAmount">
          <el-input v-model="htform.insuranceAmount" autocomplete="off" size='small'
            oninput="htform.insuranceAmount=htform.insuranceAmount.replace(/^0+(\d)|[^\d]+/g,'')"></el-input>
        </el-form-item>
        <el-form-item label="合同文件地址" label-width="100px" class="uploadMain">
          <el-input class="uploadInput" v-model="insuranceFile" autocomplete="off" size='small' readonly>
            <i slot="suffix" class="el-input__icon el-icon-circle-close" @click="handleClick()"></i>
          </el-input>
          <el-upload class="upload-demo" action="#" accept=".pdf" :auto-upload="false" :limit="1" :show-file-list="false" :on-change="beforeUpload" :file-list="fileList"
            v-if="fileList.length==0">
            <el-button size="small" type="primary" :loading='loading'>点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="addTrue('htform')" v-if="title == '添加'">确 定</el-button>
        <el-button type="primary" @click="editTrue('htform')" v-if="title == '编辑'">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import util from '@/libs/util'
import { getselectEleInsuranceList, getaddEleInsurance, getselectUseOrgList, geteditEleInsurance, getdelEleInsurance, getselectEleInsuranceItemList, getaddEleInsuranceItemList, geteditContractItem, getdelEleInsuranceItemList, getsselectMaintEleList } from '@/api/orglist'
import { getUploadFile } from '@/api/public'
export default {
  components: {

  },
  data () {
    return {
      rules: {
        insuranceName: [
          { required: true, message: '请输入合同名称', trigger: 'blur' }
        ],
        insuranceNo: [
          { required: true, message: '请输入合同编号', trigger: 'blur' }
        ],
        insuranceStarttime: [
          { required: true, message: '请选择合同开始时间', trigger: 'change' }
        ],
        insuranceEndtime: [
          { required: true, message: '请选择合同结束时间', trigger: 'change' }
        ],
        useOrgId: [
          { required: true, message: '请选择使用单位', trigger: 'change' }
        ],
        insuranceAmount: [
          { required: true, message: '请输入保险金额', trigger: 'blur' }
        ],
        insuranceId: [
          { required: true, message: '请选择保险公司', trigger: 'change' }
        ],
      },
      insuranceArr: [
        {
          value: 10,
          label: '中国平安'
        },
        {
          value: 11,
          label: '中国人寿'
        },
        {
          value: 12,
          label: '太平洋保险'
        },
        {
          value: 13,
          label: '中国人保'
        },
        {
          value: 14,
          label: '新华保险'
        },
      ],
      loading: false,
      insuranceFile: null,
      fileList: [],
      innerVisible: false,
      value: '',
      eletableData: [],
      options: [],
      temitemform: {},
      formLabelWidth1: '120px',
      formLabelWidth: '120px',
      form: {
        eleTypeId: '',
        maintTypeId: '',
        templateName: '',
        templateRemark: ''
      },
      htform: {
      },
      dialogVisible: false,
      activeName: 'first',
      pagination: {
        pageTotal: 0,
        pageSize: 10,
        pageNum: 1,
      },
      pagination1: {
        pageTotal: 0,
        pageSize: 10,
        pageNum: 1,
      },
      pagination2: {
        pageTotal: 0,
        pageSize: 10,
        pageNum: 1,
      },
      formInline: {
      },
      title: null,
      htdialog: false,
      temData: [],
      tableData: [],
      htxId: null,
      id: null,
      multipleSelection: [],
    }
  },
  mounted () {
    this.gettableData()
  },
  methods: {
    selectable (row, index) {
      if (!row.insuranceOrderId) {
        return true
      }
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    // 点击下载
    download (url) {
      window.open(util.fileIP + url)
    },
    // 上传文件
    beforeUpload (file, fileList) {
      console.log(file)
      if (file.type != "" || file.type != null || file.type != undefined) {
        const isLt5M = file.size / 1024 / 1024 < 5 //这里做文件大小限制
        if (!isLt5M) {
          this.fileList = []
          this.$message('上传文件大小不能超过 5MB!')
          return false
        }
        this.fileList = []
        let formData = new FormData()
        formData.append('file', file.raw)
        formData.append('bucketName', 'contract')
        this.loading = true
        getUploadFile(formData).then(res => {
          if (res.data.code == '200') {
            this.loading = false
            this.$message({
              type: 'success',
              message: '文件上传成功!'
            })
            this.htform.insuranceFile = res.data.data.id,
              this.insuranceFile = file.name
            this.fileList = fileList
          }
        })
      }
    },
    // editItemTrue () {
    //   geteditContractItem({
    //     contractId: this.id,
    //     eleCode: this.temitemform.eleCode,
    //     id: this.htxId
    //   }).then(res => {
    //     if (res.data.code == '200') {
    //       this.getContractInfo()
    //       this.handleClose2()
    //       this.$message({
    //         type: 'success',
    //         message: '编辑成功!'
    //       })
    //     }
    //   })
    // },
    // editHtx (rows) {
    //   this.title = '编辑'
    //   this.htxId = rows.id
    //   this.innerVisible = true
    //   const params = JSON.parse(JSON.stringify(rows))
    //   this.temitemform = params
    // },
    addItemTrue () {
      if (this.multipleSelection.length > 0) {
        let query = this.multipleSelection.map((item) => {
          return item.eleCode
        })
        const params = {
          orderId: this.id,
          eleCode: query
        }
        getaddEleInsuranceItemList(params).then(res => {
          if (res.data.code == '200') {
            this.getContractInfo()
            this.handleClose2()
            this.$message({
              type: 'success',
              message: '添加成功!'
            })
          }
        })
      } else {
        this.$message({
          type: 'info',
          message: '请选择电梯'
        })
      }

    },
    deleteHtx (id) {
      this.$confirm('是否确认删除选中的设备?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          ids: [id]
        }
        getdelEleInsuranceItemList(params).then(res => {
          if (res.data.code == '200') {
            this.getContractInfo()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          } else {
            this.$message({
              type: 'warning',
              message: res.data.msg
            })
          }
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    //添加合同享
    getAddhtx () {
      this.title = '添加'
      this.innerVisible = true
      this.geteleList()
    },
    geteleList () {
      getsselectMaintEleList(
        {
          pageNum: this.pagination2.pageNum,
          pageSize: this.pagination2.pageSize,
          useOrgName: this.temitemform.useOrgName,
        }
      ).then(res => {
        console.log(res)
        if (res.data.code == '200') {
          this.eletableData = res.data.data.list
          this.pagination2.pageTotal = res.data.data.total
        }
      })
    },
    deleteHt (id) {
      this.$confirm('是否确认删除选中的合同?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          ids: [id]
        }
        getdelEleInsurance(params).then(res => {
          if (res.data.code == '200') {
            this.gettableData()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          } else {
            this.$message({
              type: 'warning',
              message: res.data.msg
            })
          }
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    editHt (rows) {
      console.log(rows)
      this.getUseOrgList()
      const params = JSON.parse(JSON.stringify(rows))
      this.htform = params
      if (params.fileName) {
        this.insuranceFile = params.fileName
        const fileName = params.fileName
        this.fileList.push({ name: fileName })
      }
      this.htdialog = true
      this.title = '编辑'
    },
    editTrue (htform) {
      this.$refs[htform].validate((valid) => {
        if (valid) {
          geteditEleInsurance({
            id: this.htform.id,
            useOrgId: this.htform.useOrgId,
            insuranceEndtime: this.htform.insuranceEndtime,
            insuranceStarttime: this.htform.insuranceStarttime,
            insuranceFile: this.htform.insuranceFile,
            insuranceName: this.htform.insuranceName,
            insuranceNo: this.htform.insuranceNo,
            insuranceId: this.htform.insuranceId,
            insuranceAmount: this.htform.insuranceAmount
          }).then(res => {
            if (res.data.code == '200') {
              this.gettableData()
              this.handleClose()
              this.$message({
                type: 'success',
                message: '编辑成功!'
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })

    },
    addTrue (htform) {
      this.$refs[htform].validate((valid) => {
        if (valid) {
          getaddEleInsurance({
            insuranceName: this.htform.insuranceName,
            insuranceNo: this.htform.insuranceNo,
            useOrgId: this.htform.useOrgId,
            insuranceFile: this.htform.insuranceFile,
            insuranceStarttime: this.htform.insuranceStarttime,
            insuranceEndtime: this.htform.insuranceEndtime,
            insuranceAmount: this.htform.insuranceAmount,
            insuranceId: this.htform.insuranceId
          }).then(res => {
            if (res.data.code == '200') {
              this.gettableData()
              this.handleClose()
              this.$message({
                type: 'success',
                message: '添加成功!'
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })

    },
    handleClose2 () {
      this.temitemform = {}
      this.innerVisible = false
    },
    handleClose1 () {
      this.form.eleTypeId = ''
      this.form.maintTypeId = ''
      this.dialogVisible = false
    },
    // 关闭弹框
    handleClose () {
      this.htform = {}
      this.htdialog = false
      this.$refs.htform.resetFields()
      this.handleClick()
    },
    handleClick () {
      this.fileList = [],
        this.htform.contractFile = ''
      this.insuranceFile = null
    },
    // 获取合同表格数据
    gettableData () {
      const query = {
        insuranceName: this.formInline.insuranceName,
        useOrgName: this.formInline.useOrgName,
        insuranceNo: this.formInline.insuranceNo,
        maintOrgName: this.formInline.maintOrgName,
        insuranceOrgName: this.formInline.insuranceOrgName,
        pageNum: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
      }
      getselectEleInsuranceList(query).then(res => {
        if (res.data.code == 200) {
          this.tableData = res.data.data.list
          this.pagination.pageTotal = res.data.data.total
        }
      })
    },
    getUseOrgList () {
      getselectUseOrgList().then(res => {
        if (res.data.code == 200) {
          this.options = res.data.data
        }
      })
    },
    // 添加合同
    addContract () {
      this.title = '添加'
      this.htdialog = true
      this.getUseOrgList()
    },
    getContractInfo () {
      getselectEleInsuranceItemList({
        pageNum: this.pagination1.pageNum,
        pageSize: this.pagination1.pageSize,
        orderId: this.id,
        eleCode: this.form.eleCode,
      }).then(res => {
        console.log(res)
        if (res.data.code == 200) {
          this.temData = res.data.data.list
          this.pagination1.pageTotal = res.data.data.total
        }
      })
    },
    showTemplateInfo (rows) {
      this.dialogVisible = true
      this.form = rows
      this.id = rows.id
      this.getContractInfo()
    },
    handleSizeChange (val) {
      this.pagination.pageNum = 1
      this.pagination.pageSize = val
      this.gettableData()
    },
    handleCurrentChange (val) {
      this.pagination.pageNum = val
      this.gettableData()
    },
    handleSizeChange1 (val) {
      this.pagination.pageNum = 1
      this.pagination.pageSize = val
      this.getContractInfo()
    },
    handleCurrentChange1 (val) {
      this.pagination.pageNum = val
      this.getContractInfo()
    },
    handleSizeChange2 (val) {
      this.pagination2.pageNum = 1
      this.pagination2.pageSize = val
      this.geteleList()
    },
    handleCurrentChange2 (val) {
      this.pagination2.pageNum = val
      this.geteleList()
    },
  }
}

</script>
<style lang="less" scoped>
.addform {
  /deep/ .el-input__inner {
    width: 220px;
  }
}

.el-card {
  .el-form {
    ::v-deep .el-form-item__label {
      font-weight: 800;
    }
  }
}
.list {
  .clearfix {
    font-weight: bold;
  }
  .el-input {
    width: 300px;
  }
  .el-pagination {
    margin-top: 2vh;
    text-align: right;
  }
}
.dialog4 {
  ::v-deep .el-dialog__body {
    padding: 0 20px 30px 20px;
  }
}
</style>
